import { Token_Key, Login_Path, Auth_Code, Api_IP, Api_Prefix } from '@/config'
import { showToast } from '@/util/uniapp'
import { isNotEmpty } from '@/util/verify'
import { useUserStore } from '@/store'
import { isCheckTimeout } from '@/util/auth'

/**
 * http请求
 * */
export function post (
  url = '', params = {}, isBodyParams, contentType, notAuth, loading, errBackDelta = 0) {
  return request(
    {
      url,
      params,
      contentType,
      method: 'POST',
      notAuth,
      loading,
      errBackDelta,
      isBodyParams,
    })
}

export function get (
  url = '', params = {}, contentType, notAuth, loading, errBackDelta = 0) {
  return request(
    { url, params, contentType, method: 'GET', notAuth, loading, errBackDelta })
}

async function request ({
  url,
  params,
  contentType = 'formData',
  method,
  notAuth,
  loading,
  errBackDelta,
  isBodyParams,
}) {
  const userStore = useUserStore()
  if (userStore.token) {
    if (!notAuth && isCheckTimeout()) {
      await showToast({
        title: '登录已超时,请重新进入',
        duration: 2000,
      })
      userStore.logout()
      return
    }
  }

  if (loading) {
    uni.showLoading({ title: '加载中...' })
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: `${Api_IP}${Api_Prefix}${url}${isBodyParams
        ? ''
        : `?${serializeParams(params)}`}`,
      method,
      data: isBodyParams ? params : {},
      header: {
        [Token_Key]: notAuth ? '' : (userStore.token || ''),
        'Content-Type': contentType && contentType === 'json'
          ? 'application/json'
          : 'application/x-www-form-urlencoded',
      },
      success: async response => {
        const { statusCode, data: res } = response

        if (statusCode === Auth_Code) {
          await showToast({
            title: '登录已超时,请重新进入',
            duration: 2000,
          })
          userStore.logout()
          return false
        }

        if (statusCode !== 200) {
          await showToast({
            title: '请求失败,请检查网络状态!',
            duration: 2000,
          })
          return false
        }

        if (res.code !== 0) {
          await showToast({
            title: res.message || '请求失败!',
            duration: 2000,
          })

          if (errBackDelta) {
            uni.navigateBack({
              delta: errBackDelta,
            })
          }
          return false
        }
        if (isNotEmpty(res)) {
          if (res.code === 0) {
            resolve(res)
          } else {
            if (isNotEmpty(res.message)) {
              await showToast({
                title: res.message,
                duration: 2000,
              })
            }
            reject(res)
          }
        } else {
          await showToast({
            title: '请求失败!',
          })
          reject(res)
        }
      },
      complete: () => {
        if (loading) {
          uni.hideLoading()
        }
      },
    })
  })
}

function serializeParams (params) {
  const arr = []
  for (let p in params)
    if (params.hasOwnProperty(p)) {
      arr.push(encodeURIComponent(p) + '=' + encodeURIComponent(params[p]))
    }
  return arr.join('&')
}

